import store from '@/stores'
import type {RouteRecordRaw} from "vue-router";

// 关闭tab
export const closeTab = (router: any, tab: any) => {

    if (tab && tab.meta && tab.meta.affix) {
        return
    }

    store.tabsStore.delView(tab)
    toLastView(router, store.tabsStore.visitedViews, tab)
}

// 关闭其他tabs
export const closeOthersTabs = (router: any, tab: any) => {
    router.push(tab)
    store.tabsStore.delOthersViews(tab)
}

// 关闭全部tabs
export const closeAllTabs = (router: any, tab: any) => {
    store.tabsStore.delAllViews()
    toLastView(router, store.tabsStore.visitedViews, tab)
}

// 跳转到最后一个tab
export const toLastView = (router: any, visitedViews: any[], view: any) => {
    const latestView = visitedViews.slice(-1)[0]
    if (latestView) {
        router.push(latestView.fullPath)
    } else {
        if (view.name === 'Home') {
            router.replace({path: '/redirect' + view.fullPath})
        } else {
            router.push('/')
        }
    }
}

export const findMenu = (id: string) => {
    let menus = store.routerStore.menuRoutes;
    let menu = findMenuItem(menus, id);
    return menu;
}
// @ts-ignore
export const findMenuItem = (menus: RouteRecordRaw[] | undefined, id: string) => {

    if (menus) {
        for (let i = 0; i < menus.length; i++) {
            // @ts-ignore
            if (menus[i] && menus[i].meta && menus[i].meta.id && menus[i].meta.id == id) {
                return menus[i];
            }
            // @ts-ignore
            if (menus[i].children != undefined && menus[i].children.length > 0) {
                const backMenu: any = findMenuItem(menus[i].children, id);
                if (backMenu != null) {
                    return backMenu;
                }
            }
        }
    }
    return null;
}


export const findMenuByUrl = (url: string) => {
    let menus = store.routerStore.searchMenu;
    let menu = menus.find((item: RouteRecordRaw) => {
        return item.meta && item.meta.url === url;
    })
    return menu;
}
